/**
 * $Id: ConnectionUtil.java 3 2011-09-05 21:38:37Z adriftrock@gmail.com $
 */

package com.swehr.utils;

import com.jolbox.bonecp.BoneCPDataSource;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Rock Huang
 * @version 0.1
 */
public class ConnectionUtil {
    private static Logger logger = Logger.getLogger(ConnectionUtil.class);

    private static final String dbUrl = "jdbc:h2:file:~/store/swehr";
    private static final String dbUser = "swehr";
    private static final String dbPwd = "swehr";
    private static final String dbDriver = "org.h2.Driver";

    private static BoneCPDataSource ds = null;

    private static ConnectionUtil selfInstance = null;

    private ConnectionUtil() {
        if ( ds == null) {
            initDataSource();

        }
    }

    private void initDataSource() {
        /* For BoneCP configuration */
        ds = new BoneCPDataSource();
        ds.setDriverClass(dbDriver);
        ds.setJdbcUrl(dbUrl);
        ds.setUsername(dbUser);
        ds.setPassword(dbPwd);
        ds.setMaxConnectionsPerPartition(10);
        ds.setTransactionRecoveryEnabled(true);
//        ds.setStatementsCacheSize(2);

        ds.setPoolAvailabilityThreshold(0);
    }

    public static ConnectionUtil getInstance() {
        if (selfInstance == null)
            selfInstance = new ConnectionUtil();
        return selfInstance;
    }

    public Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

}
